import { Component } from 'react';

import {
  TabBar,
  ActionSheet,
  Toast,
  Popup,
  CalendarField,
  Group,
  Boxs,
  Tab,
  SearchBar,
  Grid,
  Slide,
  Button,
  ScrollList,
  Avatar,
  Dialog,
  Badge,
  Datetime
} from 'saltui';
const { HBox, Box } = Boxs;
const {
  IconButton,
  ButtonGroup,
} = Button;
import BottomTab from '../../tab';
import './PageHome.less';



import {URLS,nodataIcon} from '../../../app/variables';

import DB from '../../../app/db';


let tabPage = '0';


const Item  =  React.createClass({
  getInitialState(){ 
    let canToAnswer=false;
    if(this.props.publish==1 && (this.props.answerStatus=='1'||this.props.answerStatus=='4') && this.props.type=='questionnaireExam' &&(
      (this.props.noLimit==1 && (this.props.grade<this.props.passScore||(!this.props.passScore && this.props.passScore!="0"))) 
      ||(this.props.noLimit==0 && (this.props.grade<this.props.passScore||(!this.props.passScore&&this.props.passScore!="0")) && this.props.answerNum<this.props.answerNumSet)
      ||(this.props.noLimit!=0 && this.props.noLimit!=1 && this.props.grade<this.props.passScore))){
      canToAnswer=true
    }
    return {
      canToAnswer: canToAnswer
    }
  },
  ques_info:function(){
    let t = this;
    let id = this.props.id;
    if(this.props.addClickAble){
      if(this.props.answerStatus == "3"){
        location.hash='questionnaire/back_reason/'+this.props.id+"/"+this.props.statusId+"/view";
      }else if(this.props.answerStatus == "4"){
        Toast.show({
          type: 'fail',
          content: '试卷正在评卷中，请稍后查看！',
        });
      }else{
        DB.QuesModuleAPI.entityIsExist({id:id}).then((content) => {
          if(content == 'exist'){
            let type = t.props.type;
            let endDate = t.props.endDate;
            if(endDate != null) endDate = endDate.replace(/\-/g, "/");//IOS对时间字符串需要处理,"-"替换成"/"       
            if(type == 'questionnaireExam'){
              if(t.props.answerStatus == "1"){
                location.hash='questionnaire/exam_view/'+id+"/"+this.state.canToAnswer;
                return ;
              }
              //是否有结束时间
              if(endDate != null && endDate != ""){
                let nowDate = new Date();
                let enDate = new Date(endDate);
                //结束时间小于等于当前时间
                if(enDate <= nowDate){
                  let msg = '抱歉！此问卷已经于 ' + endDate.substring(0,16).replace(/\//g, "-") + ' 结束，不能再作答！';
                  Dialog.alert({
                    title: '提示',
                    content: msg,
                    onConfirm() {
                      return;
                    },
                  });
                  return;
                }
              }
              location.hash='questionnaire/ques_info/'+id+"/0"+"/"+this.state.canToAnswer;
            }else{
              location.hash='questionnaire/ques_info/'+id+"/0"+"/"+this.state.canToAnswer;
            }
          }else{
            Toast.show({
                type: 'error',
                content: '当前数据已删除',
            });
            t.props.refresh();
          }
        }).catch((error) => {
        });
      }
    }else{
      this.props.changeClickAble();
    }  
  },

  ques_infoOnce:function(){
    let t = this;
    let id = this.props.id;
    if(this.props.addClickAble){
      if(this.props.answerStatus == "3"){
        location.hash='questionnaire/back_reason/'+this.props.id+"/"+this.props.statusId+"/view";
      }else if(this.props.answerStatus == "4"){
        Toast.show({
          type: 'fail',
          content: '试卷正在评卷中，请稍后查看！',
        });
      }else{
        DB.QuesModuleAPI.entityIsExist({id:id}).then((content) => {
          if(content == 'exist'){
            let type = t.props.type;
            let endDate = t.props.endDate;
            if(endDate != null) endDate = endDate.replace(/\-/g, "/");//IOS对时间字符串需要处理,"-"替换成"/"       
            if(type == 'questionnaireExam'){
          
              //是否有结束时间
              if(endDate != null && endDate != ""){
                let nowDate = new Date();
                let enDate = new Date(endDate);
                //结束时间小于等于当前时间
                if(enDate <= nowDate){
                  let msg = '抱歉！此问卷已经于 ' + endDate.substring(0,16).replace(/\//g, "-") + ' 结束，不能再作答！';
                  Dialog.alert({
                    title: '提示',
                    content: msg,
                    onConfirm() {
                      return;
                    },
                  });
                  return;
                }
              }
              location.hash='questionnaire/ques_info/'+id+"/0"+"/"+this.state.canToAnswer;
            }else{
              location.hash='questionnaire/ques_info/'+id+"/0"+"/"+this.state.canToAnswer;
            }
          }else{
            Toast.show({
                type: 'error',
                content: '当前数据已删除',
            });
            t.props.refresh();
          }
        }).catch((error) => {
        });
      }
    }else{
      this.props.changeClickAble();
    }  
  },

  render:function() {
    let as = this.props.answerStatus;
    let statusStyle;
    switch (this.props.answerStatus) {
      case 0 : statusStyle = "z-WFC t-MR10 t-H22 t-LH22 light-badge badge-lightorange";break;
      case 1 : statusStyle = "z-WFC t-MR10 t-H22 t-LH22 light-badge badge-lightgrey";break;
      case 2 : statusStyle = "z-WFC t-MR10 t-H22 t-LH22 light-badge badge-lightgreen";break;
      case 3 : statusStyle = "z-WFC t-MR10 t-H22 t-LH22 light-badge badge-lightred";break;
      case 4 : statusStyle = "z-WFC t-MR10 t-H22 t-LH22 light-badge badge-lightgrey";break;
      case '0' : statusStyle = "z-WFC t-MR10 t-H22 t-LH22 light-badge badge-lightorange";break;
      case '1' : statusStyle = "z-WFC t-MR10 t-H22 t-LH22 light-badge badge-lightgrey";break;
      case '2' : statusStyle = "z-WFC t-MR10 t-H22 t-LH22 light-badge badge-lightgreen";break;
      case '3' : statusStyle = "z-WFC t-MR10 t-H22 t-LH22 light-badge badge-lightred";break;
      case '4' : statusStyle = "z-WFC t-MR10 t-H22 t-LH22 light-badge badge-lightgrey";break;
    }
    let typeName = '';
    switch (this.props.type){
      case 'questionnaireVote': typeName = '投票';break;
      case 'questionnaireSurvey': typeName = '调查';break;
      case 'questionnaireExam': typeName = '考试';break;
    }
    return <div>
      <Box className="t-BCf t-ML16 t-MR16 t-MT10 t-P12 t-PR0 t-R4">
        <HBox>
          <Box flex={1} className="t-LH1_4 t-PR10 t-FS16 t-omit2">{this.props.name}</Box>
          <Box onClick={this.ques_info} className={statusStyle}>{this.props.status}</Box>
          {this.state.canToAnswer?<Box onClick={this.ques_infoOnce} className="z-WFC t-MR10 t-H22 t-LH22 light-badge badge-lightorange">再次答卷</Box>:'' }
        </HBox>
        <HBox className="t-MT8 t-FCddfontblue-40">
          <Box flex={1} className="">{typeName}</Box>
          <Box className="t-PR10">{this.props.createdDate}</Box>
        </HBox>
      </Box>
    </div>;
  }
});



export default class PageHome extends Component {

 constructor(props) {
    super(props);
    setTitle('我的答卷');
    let t = this;
    let userId = document.getElementById("userHiddenId").value;
    let winHeight ;
    winHeight = getScrollHigh(1,1,0);
    this.state = {
      userId:userId,
      ableClick:true,
      winHeight:winHeight,
      search1:'',
      //搜索
      visible1: false,

      //问卷类型
      typeArr:[{'value':'questionnaireVote','text':'投票'},{'value':'questionnaireSurvey','text':'调查'},{'value':'questionnaireExam','text':'考试'}],
      //答卷状态
      statusArr:[{'value':'0','text':'待答卷'},{'value':'1','text':'已提交'},{'value':'2','text':'草稿'},{'value':'3','text':'已回退'}],

      //选择的问卷类型
      type:"",
      //选择的问卷状态
      status:"",
      //筛选条件展示位
      quesTypeArrow : false,
      quesStatusArrow : false,

      //筛选  问卷时间
      // time:null,
      startDate:null,
      endDate:null,
      addClickAble:true,
      noDataTip:'暂无数据'
    };
    
  }

  componentDidMount(){
      this.initButton();
      searchBarLimit(20);
  }
  componentWillUnmount(){
    setTitle('');
  }

  //时间格式化   YYYY-MM-DD
  formatterDate(time){
    var date = new Date(time);
    var Y = date.getFullYear() + '-';
    var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
    var D = date.getDate() < 10 ? "0" + (date.getDate()) : date.getDate();
    return Y+M+D;
  }

  changeClickAble(){
    this.setState({
      addClickAble:true
    })
  }

  //分页列表请求前
  beforeFetch1(data,form){
    this.setState({
      addClickAble:false
    });
    let search = form.value;
    if(search == undefined){
      if(form=='top'){
        this.setState({ableClick:false});
      }
      data.search = this.state.search1;
    }else{
        data.search = form.value;
    }
    // let rows = data.pageSize;
    // data.rows = rows;

    if(this.state.startDate != null && this.state.startDate != ''){
      data.startDate = this.formatterDate(this.state.startDate);
    }
    if(this.state.endDate != null && this.state.endDate != ''){
      data.endDate = this.formatterDate(this.state.endDate);

    }
    if(this.state.type != ''){
      data.quesType = this.state.type;
    }
    if(this.state.status != ''){
      data.status = this.state.status;
    }
    return data;
  }

  processData(data){
    this.setState({
      addClickAble:true
    });
    return data;
  }

  //初始化按钮
  initButton(){
    //设置帮助
    //  dd.biz.navigation.setIcon({
    //     showIcon : true,//是否显示icon
    //     iconIndex : 2,//显示的iconIndex,如上图
    //     onSuccess : function(result) {
    //         /*结构
    //         {
    //         }*/
    //         //点击icon之后将会回调这个函数
    //         location.hash='document/help_index';
    //     },
    //     onFail : function(err) {
    //     //jsapi调用失败将会回调此函数
    //     }
    // });

    }

    /*跳到帮助*/
  skipHelp(path){
    let t = this;
    var userId = this.state.userId;
    dd.util.domainStorage.setItem({
     name:'document_'+userId , // 存储信息的key值
     value:'isLogin', // 存储信息的Value值
     onSuccess : function(info) {
          t.setState({
              isMask:false
             });
          location.hash=path;
     },
     onFail : function(err) {
     }
    });
    
  }

//刷新列表
  refresh(){
    let t = this;
    let value = t.state.search1;
    if(value != "") t.refs.reportComment_ref1.fetchData({value:value});
    else t.refs.reportComment_ref1.fetchData("bottom");
  }
  //改变筛选展示状态
  changeArrow(field){
    let t = this;
    let status = t.state[field];
    t.setState({
      [field]:!status
    })
  }


  //修改标题
  changeTitle(title){
    setTitle(title);
  }
  //日期选择确认
  onOk(value,key){
    let t = this;
    if(key == "startDate" && t.state.endDate != null && t.state.endDate != ''){
      if(t.formatterDate(t.state.endDate) < t.formatterDate(value.value)){
        Toast.show({
          type: 'error',
          content: '开始日期不能大于结束日期'
        });
        return;
      }
    }
    if(key == "endDate" && t.state.startDate != null && t.state.startDate != ''){
      if(t.formatterDate(t.state.startDate) > t.formatterDate(value.value)){
        Toast.show({
          type: 'error',
          content: '结束日期不能小于开始日期'
        });
        return;
      }
    }
    t.setState({
      [key]:t.formatterDate(value.value)
    });
  }

  showSlot(id) {
    this[id].show();
  }
  render() {
    const t = this;
    let popHei=window.screen.height-60;
    const props = {
      locale: 'zh_CN',
      instantSearch: false,
      placeholder:'请输入问卷名称',
      hasHistory: true,
      searchDelay: 450,
      onEnter: (value) => { console.log(value); },
      onExit: () => { 
         t.setState({
          search1 :'',
          noDataTip:'暂无数据'
        },()=>{
           t.refs.reportComment_ref1.fetchData("top");
        });

       },
      onChange: (value) => {
       console.log('onChange');
      },
      onSearch: (value) =>{
        t.setState({
          search1 :value,
          noDataTip:'无搜索结果'
        },()=>{
          if(value != "") t.refs.reportComment_ref1.fetchData({value: value});
          else t.refs.reportComment_ref1.fetchData("top");
        });
       

      }
    };
    let winHeightStyle = {height: this.state.winHeight};
    const datetimeProps = {
      locale: 'zh-cn',
    };
    return (
      <div>  
          <div>
            <HBox className="t-BCf" vAlign="center">
              <Box flex={1}><SearchBar {...props} /></Box>
              <Box className="t-FCddblue" onClick={() => { t.setState({ visible1: true }); }}><i className="
iconfont icon-filter t-FS18 t-FCblue t-LH44 t-PR10"/></Box>
            </HBox>
                <div style={winHeightStyle}>
                    <ScrollList
                      url={URLS.getDingMyAnswerList}
                      dataType="json"
                      pageSize={10}
                      beforeFetch={this.beforeFetch1.bind(this)}
                      processData={this.processData.bind(this)}
                      noDataTip={this.state.noDataTip}
                      ref = 'reportComment_ref1'
                      noDataImage={nodataIcon}
                      currentPageKey="page"
                      >
                      <Item refresh={t.refresh.bind(t)} addClickAble={t.state.addClickAble} changeClickAble={t.changeClickAble.bind(this)}/>
                    </ScrollList>
                 </div>
          </div>
        <BottomTab activeIndex={1}/>


        <Popup
          content={
            <div className="dd-popup-mail-right" style={{width:"280px",paddingTop:0,overflow:"auto",height:popHei}}>
              <HBox vAlign="center"
                    className="t-P16 t-PT14 t-PB0 t-FS16 t-MT4" onClick={t.changeArrow.bind(t,"quesTypeArrow")}>
                <Box flex={1} className="t-FC3" >问卷类型</Box>
                <Box><i className={this.state.quesTypeArrow?"iconfont icon-arrow-down t-FCddblue":"iconfont icon-arrow-up t-FCddblue"} ></i></Box>
              </HBox>
              <HBox className={!this.state.quesTypeArrow?"t-FAC t-P12 t-PB6 t-PT6 t-fw":"t-DN"}>
                {
                  t.state.typeArr.map((item,key)=>(
                    <Box key={key} className={t.state.type == item.value?"t-BCddblue-20 t-FS14 t-FCddblue  t-PL16 t-PR16 t-LH44 t-H44 t-M4 t-calc50-8 t-R4 t-omit":"t-BCf7 t-PL16 t-FS14 t-PR16 t-LH44 t-H44 t-M4 t-calc50-8 t-R4 t-omit"} onClick={()=>{
                      if(t.state.type == item.value){
                        t.setState({type:''})
                      }else{
                        t.setState({type:item.value})
                      }
                    }}>
                      {item.text}
                    </Box>
                  ))
                }
              </HBox>
              <HBox vAlign="center"
                    className="t-P16 t-PT16 t-PB0 t-FS16"
                    onClick={t.changeArrow.bind(t,"quesStatusArrow")}>
                <Box flex={1} className="t-FC3">答卷状态</Box>
                <Box><i className={this.state.quesStatusArrow?"iconfont icon-arrow-down t-FCddblue":"iconfont icon-arrow-up t-FCddblue"} ></i></Box>
              </HBox>
              <HBox className={!this.state.quesStatusArrow?"t-FAC t-P12 t-PB6 t-PT6 t-fw":"t-DN"}>
                {
                  t.state.statusArr.map((item,key)=>(
                    <Box key={key} className={t.state.status == item.value?"t-BCddblue-20 t-FS14 t-FCddblue  t-PL16 t-PR16 t-LH44 t-H44 t-M4 t-calc50-8 t-R4 t-omit":"t-BCf7 t-PL16 t-FS14 t-PR16 t-LH44 t-H44 t-M4 t-calc50-8 t-R4 t-omit"} onClick={()=>{
                      if(t.state.status == item.value){
                        t.setState({status:''})
                      }else{
                        t.setState({status:item.value})
                      }
                    }}>
                      {item.text}
                    </Box>
                  ))
                }
              </HBox>

              <p className="t-MT20 t-ML16 t-FS16 t-FS16">创建日期</p>
              <HBox vAlign="center" className="t-PL16 t-MT10">
                <Box className="t-FC9 t-FS14">开始</Box>
                <Box  className="t-BCf7 t-LH32 t-R4 t-ML5" onClick={() => {t.showSlot('slot1');}} style={{width:'84%'}}>
                  <p className="t-FAC t-H26">{t.state.startDate} <i className="iconfont icon-calendar t-FS14 t-FCblue t-FR t-MR10"></i></p>
                  <Datetime
                    {...datetimeProps}
                    slotRef={s => this.slot1 = s}
                    title="日期选择"
                    placeholder="开始日期"
                    value={t.state.startDate}
                    columns={Datetime.YMD}
                    onConfirm={(value) => {t.onOk(value, 'startDate');}}
                    onCancel={() => {  }}
                  />
                </Box>
              </HBox>
              <div className="t-H10"></div>
              <HBox vAlign="center" className="t-PL16">
                <Box className="t-FC9 t-FS14">结束</Box>
                <Box className="t-BCf7 t-LH32 t-R4 t-col-6 t-ML5" onClick={() => {t.showSlot('slot2');}} style={{width:'84%'}}>
                  <p className="t-FAC t-H26">{t.state.endDate}<i className="iconfont icon-calendar t-FS14  t-FCblue t-FR t-MR10"></i></p>
                  <Datetime
                    {...datetimeProps}
                    slotRef={s => this.slot2 = s}
                    title="日期选择"
                    placeholder="结束日期"
                    value={t.state.endDate}
                    columns={Datetime.YMD}
                    onConfirm={(value) => { t.onOk(value, 'endDate'); }}
                    onCancel={() => {  }}
                  />
                </Box>
              </HBox>


              <div className="t-bottom-fixed" style={{borderTop:0,bottom:'0',width:'100%'}}>
                <ButtonGroup onClick={() => { Popup.hide(); }}>
                  <Button type="secondary" display="inline" onClick={() => { t.setState({type:"",status:"",startDate:'',endDate:'',noDataTip:'暂无数据'},()=>{t.refresh()}) }}>重置</Button>
                  <Button type="primary" display="inline" onClick={() => {this.setState({ visible1: false,noDataTip:'无搜索结果' });t.refresh()}}>确定</Button>
                </ButtonGroup>
              </div>
            </div>
          }
          animationType="slide-left"
          onMaskClick={() => { this.setState({ visible1: false }); }}
          visible={this.state.visible1}
        >
          {null}
        </Popup>
      </div>
      );
    }
}


